//package com.youedata.modular.filter;
//
//import cn.stylefeng.roses.core.util.ToolUtil;
//import com.youedata.base.auth.jwt.JwtTokenUtil;
//import com.youedata.config.properties.SwaggerProperties;
//import com.youedata.sys.core.auth.cache.SessionManager;
//import io.jsonwebtoken.JwtException;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.util.AntPathMatcher;
//import org.springframework.web.filter.OncePerRequestFilter;
//
//import javax.servlet.FilterChain;
//import javax.servlet.ServletException;
//import javax.servlet.http.Cookie;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//
//import static com.youedata.base.consts.ConstantsContext.getTokenHeaderName;
//
///**
// * 对客户端请求的jwt token验证过滤器
// *
// * @author fengshuonan
// * @Date 2017/8/24 14:04
// */
//@Slf4j
//public class AuthFilter extends OncePerRequestFilter {
//
//    @Autowired
//    private JwtTokenUtil jwtTokenUtil;
//
//    @Autowired
//    private SwaggerProperties swaggerProperties;
//
//    @Autowired
//    private SessionManager sessionManager;
//
//    @Override
//    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
//
//        //过滤静态资源
//        String[] regs = {"/assets/**", "/favicon.ico", "/activiti-editor/**"};
//        for (String reg : regs) {
//            if (new AntPathMatcher().match(reg, request.getServletPath())) {
//                chain.doFilter(request, response);
//                return;
//            }
//        }
//
//        //swagger相关
//        if (swaggerProperties.getApiOpen()) {
//            if (request.getServletPath().startsWith("/" + "swagger") ||
//                    request.getServletPath().equals("/" + "v2/api-docs") ||
//                    request.getServletPath().contains("springfox-swagger-ui")) {
//                chain.doFilter(request, response);
//                return;
//            }
//        }
//
//        // 首页
//        if (request.getServletPath().equals("/")) {
//            chain.doFilter(request, response);
//            return;
//        }
//
//        // login
//        if (request.getServletPath().startsWith("/login")) {
//            chain.doFilter(request, response);
//            return;
//        }
//
//        //权限校验的头部
//        String tokenHeader = getTokenHeaderName();
//        final String requestHeader = request.getHeader(tokenHeader);
//
//        String username = null;
//        String authToken = null;
//
//        // 1.从cookie中获取token
//        Cookie[] cookies = request.getCookies();
//        if (cookies != null) {
//            for (Cookie cookie : cookies) {
//                if (tokenHeader.equals(cookie.getName())) {
//                    authToken = cookie.getValue();
//                }
//            }
//        }
//
//        // 2.如果cookie中没有token，则从header中获取token
//        if (ToolUtil.isEmpty(authToken)) {
//            if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
//                authToken = requestHeader.substring(7);
//            }
//        }
//
//        // 3.通过token获取用户名
//        if (ToolUtil.isNotEmpty(authToken)) {
//            try {
//                username = JwtTokenUtil.getJwtPayLoad(authToken).getAccount();
//            } catch (IllegalArgumentException | JwtException e) {
//                //请求token为空或者token不正确，忽略，并不是所有接口都要鉴权
//            }
//        }
//
//        // 4.如果账号不为空，并且没有设置security上下文，就设置上下文
//        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
//
//            //从缓存中拿userDetails
//            UserDetails userDetails = sessionManager.getSession(authToken);
//            if (userDetails == null) {
//
//                //删除cookies
//                Cookie[] tempCookies = request.getCookies();
//                if (null != tempCookies) {
//                    for (Cookie cookie : tempCookies) {
//                        if (tokenHeader.equals(cookie.getName())) {
//                            Cookie temp = new Cookie(cookie.getName(), "");
//                            temp.setMaxAge(0);
//                            response.addCookie(temp);
//                        }
//                    }
//                }
//
//                //跳转到登录超时
//                response.setHeader("Guns-Session-Timeout", "true");
//                request.getRequestDispatcher("/global/sessionError").forward(request, response);
//
//                return;
//            }
//
//            //创建当前登录上下文
//            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
//                    userDetails, null, userDetails.getAuthorities());
//            SecurityContextHolder.getContext().setAuthentication(authentication);
//        }
//
////        request.setAttribute(FILTER_APPLIED, true);
//        chain.doFilter(request, response);
//
//
////        //检查jwt的token
////        final String requestHeader = request.getHeader("Cookie");
////        logger.info("请求头信息-{}", requestHeader);
////        String authToken = null;
////        if (requestHeader != null) {
////            authToken = requestHeader.split(ConstantsContext.getTokenHeaderName() + "=")[1];
////            //验证token是否过期,包含了验证jwt是否正确
////            try {
////                logger.info("请求头token信息-{}", authToken);
////                boolean flag = jwtTokenUtil.isTokenExpired(authToken);
////                if (flag) {//验证token是否失效
////                    RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_EXPIRED.getCode(), BizExceptionEnum.TOKEN_EXPIRED.getMessage()));
////                    return;
////                }
//////                if (!redisUtil.hasKey(authToken)) {//根据当前的token比对下Redis存储信息
//////                    RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_EXPIRED_NOT_EXIST.getCode(), BizExceptionEnum.TOKEN_EXPIRED_NOT_EXIST.getMessage()));
//////                    return;
//////                }
////            } catch (JwtException e) {
////                e.printStackTrace();
////                //有异常就是token解析失败
////                RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
////                return;
////            }
////        } else {
////            //header没有带userToken字段
////            RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
////            return;
////        }
//////        String userStr = redisUtil.get(authToken);
//////        logger.info("请求头token信息-{},用户信息-{}", authToken, userStr);
//////        if (StringUtils.isBlank(userStr)) {
//////            RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_EXPIRED_NOT_EXIST.getCode(), BizExceptionEnum.TOKEN_EXPIRED_NOT_EXIST.getMessage()));
//////            return;
//////        }
////        chain.doFilter(request, response);
//    }
//}